
(function ($, win, doc, body) {
    var supportedClient = true,
        jqTemplateId = "jqTemplateActionMenu",
        openedClassname = "tl-acnmenu-opened",
        disabledClassname = "disabled",
        $body = $(body);

    // check client
    supportedClient = true;

    // callbacks
    function onBodyClick (evt) {
        $body.unbind("click", onBodyClick).find("div." + openedClassname)
          .removeClass(openedClassname).find("div.menu-container").hide();
    }

    function onTitleClick (evt) {
        onBodyClick();
        var $acnmenu = $(this).parents('div.menu-action:first');

        if ($acnmenu.hasClass(openedClassname) || $acnmenu.hasClass(disabledClassname)) {
          return undefined;
        }

        $acnmenu.addClass(openedClassname).find("div.menu-container:first").show();
        setTimeout(bindBodyEvents, 0);
    }

    function bindBodyEvents () {
        $body.bind("click", onBodyClick);
    }

    function bindEvents ($acnmenu) {
        $acnmenu.find("span.menu-title:first")
          .bind("click", onTitleClick);
    }

    function initActionMenu ($btns, opts) {
        var $acnmenu = $.tlTmpl(jqTemplateId, opts);
        $btns.filter(":first").before($acnmenu);
        $acnmenu.find("div.menu-list:first").append($btns.addClass("menu-item"));

        bindEvents($acnmenu);
    }

    $.fn.tlActionMenu = function (opt) {
        opt = $.extend({
            title: "",
            classname: ""
        }, opt);

        if (supportedClient) {
            initActionMenu(this, opt);
        }

        return this;
    };
})(jQuery, window, document, document.body);
